import { Collection, Document, Sort } from 'mongodb';
import BaseModel from './MongoBaseModel';

interface IStorys {
  id?: any;
  name?: string;
  [propName: string]: any;
}

class Model extends BaseModel<IStorys> {
  constructor() {
    super('storys');
  }

  async updateAdd(data: IStorys, query: IStorys) {
    const db = await this.init();
    return db.updateOne(
      query,
      {
        $set: data,
      },
      {
        upsert: true,
      },
    );
  }

  async updatePush(data: IStorys, query: IStorys) {
    const db = await this.init();
    return db.updateOne(query, {
      $push: data,
    });
  }

  async getListPagination(query, sortFields, pageIndex = 1, pageSize = 10) {
    const db = await this.init();
    let ret = await this.unionFind(query || {});
    const total = await db.countDocuments(query);
    const page = pageIndex;
    const size = pageSize > 100 ? 100 : pageSize;
    if (sortFields) {
      ret = ret.sort(sortFields);
    }
    ret = ret.skip(size * (page - 1)).limit(size);
    const r = await ret.toArray();
    return {
      total,
      data: r,
    };
  }

  async unionFind(query) {
    const db = await this.init();
    return db.aggregate([
      {
        $match: query,
      },
      {
        $lookup: {
          from: 'storyWithproject',
          localField: 'id',
          foreignField: 'id',
          as: 'relation_projects',
        },
      },
    ]);
  }

  async getListUnion(query?: IStorys, sortFields?: Sort) {
    let ret = await this.unionFind(query || {});
    if (sortFields) {
      ret = ret.sort(sortFields);
    }
    return ret.toArray();
  }

  /**
   * 联合排期表。查询需求的排期
   */
  async unionStorySchedule(query) {
    const db = await this.init();
    return db
      .aggregate([
        {
          $match: query,
        },
        {
          $lookup: {
            from: 'schedule',
            localField: '_id',
            foreignField: 'storyId',
            as: 'developerList',
          },
        },
        {
          $project: {
            _id: 0,
            storyId: '$_id',
            developOwner: '$developOwner',
            developEnv: 1,
            timeNodes: 1,
            testArea: 1,
            developerList: '$developerList',
          },
        },
      ])
      .toArray();
  }
}

export default new Model();
